package com.heima.behavior.service.impl;


import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //0.参数判空
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //1.获取参数
        Long articleId = dto.getArticleId();
        Short operation = dto.getOperation();//0点赞,1取消点赞

        Integer userId = AppThreadLocalUtil.getUser().getId();
        if(userId==null||userId==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.查重
        if(operation==0){
            //2.1点赞
            Object o = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString());
            if(o!=null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"已点赞");
            }
            //添加点赞记录
            Long timeMillis = System.currentTimeMillis();
            cacheService.hPut(BehaviorConstants.LIKE_BEHAVIOR+articleId,userId.toString(), timeMillis.toString());
        }else if(operation==1)
            //2.2取消点赞
            cacheService.hDelete(BehaviorConstants.LIKE_BEHAVIOR+articleId,userId.toString());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
